import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Router} from '@angular/router';
import {environment} from '../../../environments/environment';
import {NzModalService} from 'ng-zorro-antd';
import {catchError} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  loginUrl = 'login';
  redirectUrl = '/admin';

  constructor(private http: HttpClient, private router: Router, private modalService: NzModalService) {
  }

  auth() {
    window.location.href =  environment.SERVER_AUTH + 'callback?callback=' +  window.location.href ;
  }

    getAuthInfo(): boolean {
     sessionStorage.clear();
     this.http.get('user').toPromise().then((user) =>{
       const us = JSON.parse(JSON.stringify(user));
       if (!us.success) {
         this.modalService.info({nzTitle: '会话失效！',nzContent: '<b style="color: red;">请重新登录！</b>', nzOkText: '确认', nzOkType: 'danger',
           nzOnOk: () => {
             this.auth();
           },
         });
       } else {
         this.setToken(us.data.details.tokenValue);
         this.router.navigateByUrl(this.redirectUrl || this.loginUrl);
         return false;
       }
     });
     return  true;
  }

  exit(router: Router): void {
    sessionStorage.clear();
    this.redirectUrl = router.url;
    this.router.navigateByUrl(this.loginUrl);
  }

  getToken(): string {
    return sessionStorage.getItem('access_token');
  }

  setToken(token: string): void {
    sessionStorage.setItem('access_token', token);
  }
}
